﻿#region Copyrights Notice
//©2009 Microsoft Corporation.  All rights reserved.
//This portal design is based on the design and some code from DropThings.com which is also licensed under an MS-PL license.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Net;

using System.Xml;
using System.Xml.Linq;
using Microsoft.InformationSecurity.CISF.Portal.Business.PortalFramework;
using Microsoft.Security.Application;
using System.Web.Caching;
using System.Configuration;

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Widgets
{
    public partial class RSS : System.Web.UI.UserControl, IWeblet
    {
        private IWebletContainer _WebletContainer;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this._WebletContainer.FirstTime)
                this.LoadRSSView(sender, e);
        }

        protected void LoadRSSView(object sender, EventArgs e)
        {
            this.ShowFeeds();
            this.RSSMultiview.ActiveViewIndex = 1;
            this.RSSWidgetTimer.Enabled = false;
        }
        void IWeblet.OnControlInitilize(IWebletContainer webContainer)
        {
            this._WebletContainer = webContainer;
        }
        void IWebletActions.UpdateSettings()
        {

        }

        private XElement m_xmlStorage;
        private XElement State
        {
            get
            {
                if (m_xmlStorage == null)
                {
                    string tmpStr = string.Empty;
                    tmpStr = this._WebletContainer.Restore();
                    if (!tmpStr.Equals(string.Empty))
                        m_xmlStorage = XElement.Parse(tmpStr);
                }
                return m_xmlStorage;
            }
        }

        public string Url
        {
            get { return State.Element("url").Value; }
            set { State.Element("url").Value = value; }
        }

        public int Count
        {
            get { return State.Element("count") == null ? 3 : int.Parse(State.Element("count").Value); }
            set
            {
                if (State.Element("count") == null)
                    State.Add(new XElement("count", value));
                else
                    State.Element("count").Value = value.ToString();
            }
        }

        private void ShowFeeds()
        {
            string url = Url;
            int count = Count;

            var feed = Cache[url] as XElement;
            if (feed == null)
            {
                try
                {
                    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                    request.Timeout = 5000;

                    //Read the proxy name from config
                    string ProxyName = ConfigurationManager.AppSettings["WebProxyName"].ToString();
                    request.Proxy = new WebProxy(ProxyName, true);

                    using (WebResponse response = request.GetResponse())
                    {
                        XmlTextReader reader = new XmlTextReader(response.GetResponseStream());

                        feed = XElement.Load(reader);

                        if (feed == null) return;

                        Cache.Insert(url, feed, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
                    }
                }
                catch
                {
                    //Clear the previous result set.
                    FeedList.DataSource = null;
                    FeedList.DataBind();

                    //set the error message
                    lblResults.Text = "<img src='images/warning.png' width='32' align='middle'></img> " + "Error fetching data from the RSS Feed. Check the URL and try again!";
                    return;
                }
            }

            try
            {
                XNamespace ns = "http://www.w3.org/2005/Atom";

                // see if RSS or Atom
                if (feed.Element("channel") != null)
                    FeedList.DataSource = (from item in feed.Element("channel").Elements("item")
                                           select new
                                           {
                                               title = item.Element("title").Value,
                                               link = item.Element("link").Value,
                                               description = item.Element("description").Value
                                           }).Take(this.Count);

                else if (feed.Element(ns + "entry") != null)
                    FeedList.DataSource = (from item in feed.Elements(ns + "entry")
                                           select new
                                           {
                                               title = item.Element(ns + "title").Value,
                                               link = item.Element(ns + "link").Attribute("href").Value,
                                               description = item.Element(ns + "content").Value
                                           }).Take(this.Count);

                FeedList.DataBind();

                //Clear if there is any previous error...
                lblResults.Text = string.Empty;
            }
            catch
            {
                //Clear preivous results...
                FeedList.DataSource = null;
                FeedList.DataBind();

                //Display error messgae.
                lblResults.Text = "<img src='images/warning.png' width='32' align='middle'></img> " + "Error fetching data from the RSS Feed. Check the URL and try again!";
            }
        }

        void IWebletActions.DisplaySettings(bool bDisplay)
        {
            SettingsPanel.Visible = bDisplay;
            if (bDisplay)
            {
                FeedUrl.Text = this.Url;
                FeedCountDropDownList.SelectedIndex = -1;
                FeedCountDropDownList.Items.FindByText(this.Count.ToString()).Selected = true;
            }
            else
            {
                this.Count = int.Parse(FeedCountDropDownList.SelectedValue);
                this.Url = FeedUrl.Text;
                this.SaveState();
                this.ShowFeeds();
            }
        }


        void IWebletActions.Minimize()
        {
        }
        void IWebletActions.Maximize()
        {
        }
        void IWebletActions.Close()
        {

        }
        void IWebletActions.MaximizeToFullScreen()
        {
        }

        protected void SaveSettings_Click(object sender, EventArgs e)
        {
            this._WebletContainer.DisplaySettings(false);
        }

        private void SaveState()
        {
            if (this.State == null)
                return;

            StringBuilder builder = new StringBuilder();
            XmlTextWriter writer = new XmlTextWriter(new StringWriter(builder));
            this.State.WriteTo(writer);

            var xml = builder.ToString();
            this._WebletContainer.Save(xml);
        }
    }
}